﻿using AutoMapper;
using B.S.ProductionProject.Domain;
using B.S.ProductionProject.ErrorCode;
using B.S.ProductionProject.Write.WebAPI.Applications.Commands.ProductionPlanningCommand;
using MediatR;
using SqlSugar;

namespace B.S.ProductionProject.Write.WebAPI.Applications.CommandHandlers.ProductionPlanningCommandHandler
{
    public class AddProductionPlanningCommandHandler : IRequestHandler<AddProductionPlanningCommand, APIResult<object>>
    {
        private readonly IMapper _mapper;
        private readonly ISqlSugarClient _db;
        private readonly IConfiguration _configuration;

        public AddProductionPlanningCommandHandler(IMapper mapper, ISqlSugarClient db, IConfiguration configuration)
        {
            _mapper = mapper;
            _db = db;
            _configuration = configuration;
        }

        public async Task<APIResult<object>> Handle(AddProductionPlanningCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.code = APIResultCode.success;
            result.msg = "生产计划添加成功";

            // 获取当前年月
            string yearMonth = DateTime.Now.ToString("yyyyMMddHHmmss");
            string prefix = "SCJH" + yearMonth;

            var model = _mapper.Map<ProductionPlanning>(request);

            model.DocumentNo = prefix;

            // 使用 ExecuteReturnIdentityAsync 方法插入数据并返回自增主键
            int productionPlanningId = await _db.Insertable(model).ExecuteReturnIdentityAsync();

            // 将主键添加到结果中
            result.data = new { productionPlanningId };

            return await Task.FromResult(result);
        }
    }
}